import axios from "axios"
import args from "../config/args"
import store from "../store"
import { ShowTip } from "../utils/utils"



// 统一异常处理
axios.interceptors.response.use(null, async function axiosRetryInterceptor(error) {

    if (error.response.status != 401) {
        ShowTip.hideLoading()
        return await Promise.reject(error)
    }

    if (error.response.status == 401) {
        let token = await MyHttp.reset_and_get_token()
        error.config.data.set('token', token)
    }
    error.config.__retryCount = error.config.__retryCount || 0
    error.config.__retryCount += 1
    if (error.config.__retryCount >= 3) {
        console.log(`url:${error.config.url}重发达到最大次数,停止重发`)
        ShowTip.hideLoading()
        return await Promise.reject(error)
    } else {
        console.log(error)
        // console.log(`url:${error.config.url}开始重发,次数:${error.config.__retryCount},状态:${error.status},data:${JSON.stringify(error.config)}`)
        return await new Promise(function (resolve) {
            return setTimeout(function () {
                return resolve(axios(error.config))
            }, 1000)
        })
    }
})

class HTTP {

    constructor(base_url){
        this.base_url = base_url
    }

    async request({ url, method, data, content_type}) {

        return await axios.request({
            url: `${this.base_url}${url}`,
            headers: {
                'content-type': content_type ? content_type : 'multipart/form-data'
            },
            method: method ? method : 'POST',
            data: data,
        })
    }

    async post(url, data, content_type) {
        return await this.request({
            url,
            content_type,
            data: {
                token: HTTP.get_token(),
                ...data
            }
        })
    }

    async reset_and_get_token() {
        let result = await this.request({
            url: '/token/get',
            data: {
                account: store.state.user.account,
                password: store.state.user.password
            }
        })
        
        HTTP.set_token(result.data.token)
        return result.data.token
    }

    static  set_token(token){ // 应该存到store中比较好
        store.commit('setToken', token)
        // window.localStorage.setItem('token', token)
    }

    static  get_token(){
        // return window.localStorage.getItem('token')
        return store.state.user.token
    }
}


const MyHttp = new HTTP(`${args.base_url}/v1`)

const MyHttpProxy = new HTTP(`${args.base_url_proxy}/v1`)


class Uploader {

    static postfix_url  = `/resource/upload`

    static async resource(type, data){
        data.type = type
        return await MyHttpProxy.post(Uploader.postfix_url, data)
    }
}


class Resource{
    /**
     * 资源的更删改查 API，具体的模型中实现
     */

    static postfix_url = `/resource`
    
    static async get(type, id){
        let result =  await MyHttp.post(`${Resource.postfix_url}/get`, {type, id})
        return result.data
    }

    static async gets(type, offset, limit){
        let result = await MyHttp.post(`${Resource.postfix_url}/gets/pure`, {type, offset, limit})
        return result.data

    }

    static async del(type,id){
        return await MyHttp.post(`${Resource.postfix_url}/del`, {type, id})
    }

    static async getCatalog(video_id){
        return (await MyHttp.post(`${Resource.postfix_url}/catalog`, {id: video_id})).data
    }

    // static async update(type, id, data){
    //     return await MyHttp.post(`${Resource.base_url}/update`, data)
    // }

}


class Searcher {
/**
 * 应该属于model的行为 还是API，抽象的是API，模型是更具体的
 */
    static postfix_url = `/resource/search`
    static async search(type, resource_id, key) {
        return (await MyHttp.post(Searcher.postfix_url, {type, id: resource_id, key})).data
    }
}





export {
    Uploader,
    Searcher,
    Resource,
    MyHttp,
    MyHttpProxy
}
